package com.edu.controller;

import com.edu.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @RequestMapping("/userTest")
    public Object getUser(User user, Model model){
        System.out.println(user);
        model.addAttribute("user",user);
        return "showUser.jsp";
    }

    @RequestMapping("/register")
    public Object addUser(@Valid User user,BindingResult bindingResult,Model model ){
        Map<String,String> map = new HashMap<>();
        if (bindingResult.hasErrors()) {
            List<FieldError> errors = bindingResult.getFieldErrors();
            for (FieldError error : errors) {
                map.put(error.getField(),error.getDefaultMessage());
            }
            model.addAttribute("msg",map);
            return "register.jsp";
        }
        model.addAttribute("user",user);
        return "showUser.jsp";
    }
}
